<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/5/13
 * Time: 12:15
 */

namespace common\service;
use backend\models\Baseagency;
use backend\models\Baseconfigs;
use backend\models\Basemessages;
use backend\models\Baseorders;
use backend\models\PlayerTbl;
use yii;

class ProcedureService
{
    public function buildProcedure($orderId)
    {
        $order = Baseorders::findOne(['OrderId'=>$orderId]);
        $user = PlayerTbl::findOne(['PlayerID'=>$order->UserId]);
        $sql = "select *,b.ClassId as TypeID 
                from baseorders a 
                inner join baseproducts b on a.ProductId = b.ProductId and a.Amount = b.Amount 
                where OrderId = '{$orderId}'";
        $data = yii::$app->db->createCommand($sql)->queryOne();
        if (empty($order))
            return ['status'=>0, 'msg'=>'充值失败，订单编号不存在！'];
        if (empty($data))
            return ['status'=>0, 'msg'=>'充值失败，消费金额与实际消费金额不符！'];
        if ($data['PayStatus'] == 1)
            return ['status'=>0, 'msg'=>'充值失败，该订单号已完成！'];
        if (empty($data['ProductId']))
            return ['status'=>0, 'msg'=>'充值失败，售价与商品不符！'];
        if (empty($user))
            return ['status'=>0, 'msg'=>'充值失败，游戏账号不存在！'];
        $limitlevel = Baseconfigs::findOne(['CfgKey'=>'limitlevel']);
        if (empty($limitlevel))
            return ['status'=>0, 'msg'=>'网络异常，请联系管理员！'];
        $configs = Baseconfigs::findOne(['CfgKey'=>'levelfixed']);
        if (empty($configs))
            return ['status'=>0, 'msg'=>'网络异常，请联系管理员！'];
        $levelfixed = explode(',', $configs->CfgVal);
        if (count($levelfixed) <> $limitlevel->CfgVal)
            return ['status'=>0, 'msg'=>'参数配置错误，请联系管理员！'];
        $agentcy = Baseagency::findOne(['PlayerId'=>$order->UserId]);
//      ---------------------------分成提点计算---------------------------
        $iosconfig = Baseconfigs::findOne(['CfgKey'=>'ratioIos'])->CfgVal;
        $tax_ratio_ios = empty($iosconfig) ? 0.37 : $iosconfig;
        $apkconfig = Baseconfigs::findOne(['CfgKey'=>'ratioApk'])->CfgVal;
        $tax_ratio_apk = empty($apkconfig) ? 0.06 : $apkconfig;
        $tax_ratio = ($order->Description == '苹果内购') ? $tax_ratio_ios : $tax_ratio_apk;
        if (empty($agentcy)){//角色是玩家
            if (!empty($user->AgentID)){//代理下的普通玩家
                $agent = Baseagency::findOne(['PlayerId'=>$user->AgentID]);
                if ($agent){
                    $result = self::remind($orderId, $agent, $levelfixed, $tax_ratio, '玩家充值');
                }else{
                    $result =  ['status' => 1, 'msg' => '普通玩家，无代理提点分成'];
                }
            }
            else{
                $result =  ['status' => 1, 'msg' => '普通玩家，无代理提点分成'];
            }
        }else{//角色是代理
            $result =  self::remind($orderId, $agentcy, $levelfixed, $tax_ratio, '代理充值');
        }
        return $result;
    }


    public static function remind($orderId, $agentcy, $levelfixed, $tax_ratio, $remarks)
    {
        $order = Baseorders::findOne(['OrderId'=>$orderId]);
        $arr = $result =[];
        $fulldir = explode(',', $agentcy->FullDir);
        /*
         * 横向代理提点分成计算
         */
        if (count($levelfixed) <> count($fulldir)){
            foreach ($fulldir as $key=>$item) {
                $agent = Baseagency::findOne(['AgentId'=>$item]);
                for ($i = 0; $i < count($levelfixed); $i++){
                    if ($i == $agent->Level){
                        $arr[] = ['levelfixed'=>$levelfixed[$i], 'playerId'=>$agent->PlayerId, 'vary'=>$agent->Vary];
                        break;
                    }
                }
            }
            for ($j=0; $j<count($arr);$j++){
                $newarr[] = $arr[$j]['levelfixed'];
                $playerId[] = $arr[$j]['playerId'];
                $vary[] = $arr[$j]['vary'];
            }
            for ($k=0; $k < count($newarr)-1; $k++){
                $divide_into = $newarr[$k] - $newarr[$k+1];
                $amount = ($order->Amount) * (1 - $tax_ratio) * $divide_into * $vary[$k];// * (1 - 0) 代理系数为1，递减10%
                //$result[] =  $k.'级分成金额：->'.number_format($amount,2,".","").'=>'.($divide_into*100).'%'.'--'.$playerId[$k];
                $result[] = self::_arrayBatchData($orderId, $playerId[$k], $k, $order->UserId, number_format($amount,2,".",""), $divide_into, $remarks, $vary[$k]);
            }
            for ($i = 0; $i < count($levelfixed); $i++){
                if ($i == $agentcy->Level){
                    $amount = ($order->Amount) * (1 - $tax_ratio) * $levelfixed[$i] * $agentcy->Vary;// * (1 - 0) 代理系数为1，递减10%
                    //$result[] = $i.'级分成金额[购买]：->'.number_format($amount,2,".","").'=>'.($levelfixed[$i]*100).'%'.'--'.$agentcy->PlayerId;
                    $result[] = self::_arrayBatchData($orderId, $agentcy->PlayerId, $i, $order->UserId, number_format($amount,2,".",""), $levelfixed[$i], $remarks, $agentcy->Vary);
                    break;
                }
            }
        }
        /*
         * 纵向代理提点分成计算
         */else{
            foreach ($fulldir as $key=>$item){
                $playerId[] = Baseagency::findOne(['AgentId'=>$item]);
            }
            for ($i = 0; $i < count($levelfixed); $i++){
                if ($i == $agentcy->Level){
                    $amount = ($order->Amount) * (1 - $tax_ratio) * $levelfixed[$i] * $agentcy->Vary;// * (1 - 0) 代理系数为1，递减10%
                    //$result[] = $i.'级分成金额[购买]：->'.number_format($amount,2,".","").'=>'.($levelfixed[$i]*100).'%'.'--'.$agentcy->PlayerId;
                    $result[] = self::_arrayBatchData($orderId, $agentcy->PlayerId, $i, $order->UserId, number_format($amount,2,".",""), $levelfixed[$i], $remarks, $agentcy->Vary);
                    break;
                }
                $divide_into = $levelfixed[$i] - $levelfixed[$i+1];
                $amount = ($order->Amount) * (1 - $tax_ratio) * $divide_into * $playerId[$i]['Vary'];// * (1 - 0) 代理系数为1，递减10%
                //$result[] = $i.'级分成金额：->'.number_format($amount,2,".","").'=>'.($divide_into*100).'%'.'--'.$playerId[$i]['PlayerId'];
                $result[] = self::_arrayBatchData($orderId, $playerId[$i]['PlayerId'], $i, $order->UserId, number_format($amount,2,".",""), $divide_into, $remarks, $playerId[$i]['Vary']);
            }
        }
        try{
            if (empty($result)){
                return ['status' => 1, 'msg' => '普通玩家，无代理提点分成'];
            }else{
                yii::$app->db->createCommand()->batchInsert('basebonus', ['OrderId','AgentId','Level','UserId','Balance','DrawScale','DrawDate','Remarks','vary'], $result)->execute();
                //提点分成需要审核，记录写入basemessage信息里
                $message = new Basemessages();
                $message->typeId = 2;
                $message->content = '订单号：'.$orderId.',充值业务完成，未进行提点审计';
                $message->msgStatus = 0;
                $message->msgDate = date('Y-m-d H:i:s', time());
                $message->save();
                return ['status' => 1, 'msg' => '代理提点分成完成'];
            }
        }catch (\Exception $e){
            return ['status' => 0, 'msg' => '提点分成操作失败'];
        }
    }


    private static function _arrayBatchData($OrderId, $AgentId, $Level, $UserId, $Balance, $DrawScale, $remarks, $vary)
    {
        $batchData = [
            'OrderId' => $OrderId,
            'AgentId' => $AgentId,
            'Level' => $Level,
            'UserId' => $UserId,
            'Balance' => $Balance,
            'DrawScale' => $DrawScale,
            'DrawDate' => date('Y-m-d H:i:s'),
            'Remarks' => $remarks,
            'vary' => $vary,
        ];
        return $batchData;
    }
}